<script>
import FilterArea from "@/components/FilterArea.vue";
import mixins from "@/assets/js/mixins.js";
import ListArea from "@/components/ListArea.vue";
import {utils} from "@/assets/util/index.js";
import FyDialog from "@/components/FyDialog.vue";

let util = utils();

import {ElMessageBox} from "element-plus";
import {useCardKeyStore} from "@/store/cardKey/store.js";
import {mapActions} from "pinia";

export default {
  name: "Index",
  components: {ListArea, FilterArea, FyDialog},
  mixins: [mixins],
  data() {
    return {
      cardKeyFilter: {
        status: ''
      },
      keyVisible: false,
      cardKeyVisible: false,
      secretKey: '',
      card: {
        type: 'month',
        count: null
      },
      list: {
        tableData: [],
        pageNo: 1,
        pageSize: 5,
        total: 0
      },
      cardRules: {
        type: [{
          required: true,
          message: '请选择卡密类型',
          trigger: 'blur'
        }],
        count: [{
          required: true,
          message: '请输入生成数量',
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.pageType = "card";
    this._loadData();
  },
  methods: {
    ...mapActions(useCardKeyStore, ['generateKey', 'generateCard']),
    onReset() {
    },
    _generateKey() {
      ElMessageBox.confirm('确定要生成秘钥吗？生成秘钥后，请及时修改环境变量！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.generateKey().then(res => {
          if (res.code === 200) {
            this.secretKey = res.data;
            this.keyVisible = true;
          }
        })
      })
    },
    hiddenKey(key) {
      let k = "";
      for (let i = 4; i < key.length - 4; i++) {
        k += '*';
      }
      k = key.substring(0, 4) + k + key.substring(key.length - 4);
      return k;
    },
    copyText(text) {
      util.copyTextToClipboard(text);
      this.$message.success("复制成功");
    },
    buildOption() {
      let option = {
        pageNo: this.list.pageNo,
        pageSize: this.list.pageSize,
        orderBy: {
          "status": "desc"
        }
      }
      if (this.cardKeyFilter.status) {
        option.status = ['eq', this.cardKeyFilter.status];
      }
      return option;
    },
    _loadData() {
      let option = this.buildOption();
      this.onSearch(option).then(res => {
        this.list.tableData = res.list;
        this.list.total = res.total;
      })
    },
    _generateCard() {
      this.$refs.cardRef.validate(valid => {
        if (valid) {
          let option = {
            type: this.card.type,
            count: this.card.count
          }
          this.submitting = true;
          this.generateCard(option).then(res => {
            this.submitting = false;
            this.cardKeyVisible = false;
            this.$message.success("生成成功");
            this._loadData();
          }).catch(e => {
            this.submitting = false;
          })
        }
      })
    },
    handleCurrentChange(e) {
      this.list.pageNo = e;
      this._loadData();
    },
    takeCode(id) {
      this.selectById(this.pageType, id).then(res => {
        let data = res.data;
        data.status = "已被领取";
        this.update(this.pageType, data).then(r => {
          this.copyText(data['codeKey']);
          this._loadData();
        })

      });
    },
    release(data) {
      data.status = "未使用";
      this.update(this.pageType, data).then(res => {
        this._loadData();
        this.$message.success("释放成功");
      })
    }
  }
}
</script>

<template>
  <FilterArea @onSearch="_loadData" @onReset="onReset" v-if="showFilterArea">
    <template #inputBox>
      <div class="area flex-rcs">
        <label>卡密状态</label>
        <el-select v-model="cardKeyFilter.status" placeholder="请选择秘钥状态">
          <el-option value="" label="全部"></el-option>
          <el-option value="未使用" label="未使用"></el-option>
          <el-option value="已被领取" label="已被领取"></el-option>
          <el-option value="已使用" label="已使用"></el-option>
        </el-select>
      </div>
    </template>
  </FilterArea>

  <ListArea :show-default-btn="false" list-url="/category/edit"
            list-title="资源分类" @handleFilter="handleFilter">
    <template #btn-extend-item>
      <el-button type="primary" @click="_generateKey">生成秘钥</el-button>
      <el-button type="success" @click="cardKeyVisible = true">生成卡密</el-button>
    </template>
    <template #table-list>
      <el-table :data="list.tableData">
        <el-table-column label="" type="selection" width="80"></el-table-column>
        <el-table-column label="卡密" prop="codeKey"></el-table-column>
        <el-table-column width="100" label="类型" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status==='未使用'?'success':scope.row.status==='已被领取'?'warning':'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column width="180" label="创建时间" prop="createTime">
          <template #default="scope">
            <div>{{ formatDate(scope.row.createTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column width="120">
          <template #default="scope">
            <el-button v-if="scope.row.status==='未使用'" type="primary" @click="takeCode(scope.row.id)">领取
            </el-button>
            <el-button v-if="scope.row.status==='已被领取'" type="warning" @click="release(scope.row)">释放</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #table-pagination>
      <el-pagination
          @current-change="handleCurrentChange"
          :page-size="list.pageSize"
          layout="prev, pager, next"
          :total="list.total"
      />
    </template>
  </ListArea>

  <el-dialog :align-center="true" title="重要提示" v-model="keyVisible">
    <div class="keyBox">
      <div class="desc">请妥善保管秘钥，永不存储秘钥信息。一旦丢失，将无法恢复。</div>
      <div class="key">
        <label>{{ hiddenKey(secretKey) }}</label>
        <div @click="copyText" class="keyBtn" style="display:none;margin-left:10px">复制</div>
      </div>
    </div>
  </el-dialog>

  <FyDialog @close="cardKeyVisible=false" :visible="cardKeyVisible" title="卡密基础信息">
    <template #form>
      <el-form :model="card" :rules="cardRules" ref="cardRef">
        <el-form-item label="卡密类型" prop="type" required>
          <el-select v-model="card.type" placeholder="请选择卡密类型">
            <el-option value="month" label="月度卡密"></el-option>
            <el-option value="season" label="季度卡密"></el-option>
            <el-option value="year" label="年度卡密"></el-option>
            <el-option value="forever" label="永久卡密"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生成数量" prop="count" required>
          <el-input v-model="card.count" placeholder="请输入生成数量"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer-btn>
      <div>
        <el-button class="submit_btn" @click="_generateCard">
          {{ submitting ? '生成中...' : '生成卡密' }}
        </el-button>
        <el-button type="danger" @click="cardKeyVisible = false">取 消</el-button>
      </div>
    </template>
  </FyDialog>
</template>

<style lang="scss">
.keyBox {
  padding: 10px;

  .title {
    font-size: 25px;
  }

  .desc {
    font-size: 16px;
    color: #7425eb;
  }

  .key {
    font-size: 20px;
    margin-top: 10px;
    margin-bottom: 10px;
    width: fit-content;

    > label {
      cursor: pointer;
    }

    &:hover {
      .keyBtn {
        display: inline-block !important;
      }
    }

    .keyBtn {
      font-size: 13px;
      color: #294f79;
      cursor: pointer;
    }
  }
}
</style>
